/*
 * BunchMonitor.java
 * 
 * last update: 30.01.2010 by Vlad Badoiu
 * 
 * author:	Power(power@kermit.cs.pub.ro)
 *
 * Obs:
 */

package engine;
import java.util.*;

/**
 * This is a monitoring task that executes when any of the values
 * it watces has been modified
 */
class BunchMonitor implements Monitor
{
	Vector<Object> targets;
	Vector<BitVector> lastValues;
	boolean isOn;
	Executable executor; //the action it must take if trgg'd
	NameSpace ns;

	BunchMonitor(NameSpace ns, Vector<Object> targets, Executable executor){
		this.ns = ns;
		this.targets = targets;
		this.executor = executor;
		lastValues = new Vector<BitVector>();
		for (Enumeration<Object> e = targets.elements(); e.hasMoreElements(); ) {
			lastValues.addElement(null);
			((Expression)(e.nextElement())).addMonitor(this);
		}
	}

	public synchronized void trigger()
	throws InterpretTimeException
	{
		xConsole.debug("bunchmonitor " + toString() + ": trigger");
		boolean doTrigger = false;
		for (int i = 0; i < targets.size(); i++) {
			BitVector curValue = ((Expression)(targets.elementAt(i))).evaluate().getInt();
			if (curValue.compare((BitVector)(lastValues.elementAt(i))) != 0) {
				doTrigger = true;
				lastValues.setElementAt(curValue, i);
			}
		}
		if (doTrigger) {
			isOn = true;
			try {
				executor.execute();
			} catch(SimulationStoppedException ex) {
			}
			isOn = false;
		}
	}

	synchronized boolean isTriggd(){
		return isOn;
	}

	public String toString(){
		String result = "monitor(";
		for (Enumeration<Object> e = targets.elements(); e.hasMoreElements(); ) {
			result += ((Expression)(e.nextElement())).toString();
			if (e.hasMoreElements()) result += ",";
		}
		return result + ")";
	}  
}

